<template>
  <div style="height: 600px">
    <div class="flex-row-start-start" style="width: 94.99%">
      <div style="width: 90%" class="flex-row-start-center">
        <Select
          v-model="kqName"
          style="width: calc(12.5% - 10px); margin-right: 10px"
          placeholder="库区名称"
          size="large"
          clearable
          @on-change="selKqName"
        >
          <Option v-for="item in kqNameList" :key="item" :value="item">{{
            item
          }}</Option>
        </Select>
        <Select
          v-model="jzName"
          style="width: calc(12.5% - 10px); margin-right: 10px"
          placeholder="井组名称"
          size="large"
          clearable
        >
          <Option v-for="item in jzNameList" :key="item" :value="item">{{
            item
          }}</Option>
        </Select>
      </div>
      <div style="width: 10%" class="flex-row-end-center">
        <Button type="error" @click="onQuery">查询</Button>
      </div>
    </div>
    <div style="margin-top: 20px" class="flex-row-start-start">
      <div style="width: 95%">
        <Table :columns="columns" :data="tableData">
          <template slot="action" slot-scope="{ row, index }">
            <div class="flex-row-start-start">
              <Icon
                type="md-create"
                size="20"
                @click="updateItem(row, index)"
                class="hover-icon"
              ></Icon>
              <Icon
                type="md-trash"
                size="20"
                style="margin-left: 5px"
                class="hover-icon"
                @click="deleteItem(row, index)"
              ></Icon>
              <Icon type="md-podium" size="20" style="margin-left: 5px" class="hover-icon" @click="showDetail(row, index)" />
            </div>
          </template>
        </Table>
        <div
          class="flex-row-end-center"
          style="margin-top: 10px"
          v-if="totalLen > 10"
        >
          <Page

            :total="totalLen"
            :page-size="pageSize"
            show-total
            @on-change="changepage"
          />
        </div>
      </div>
      <div style="width: 5.01%">
        <!-- <div>
          <Button style="width: 65px" @click="addData">新增</Button>
        </div> -->
        <div class="flex-row-center-center">
          <Button
            style="width: 65px; margin-top: 10px"
            class="flex-row-center-center"
            @click="importExcel"
            >批量导入</Button
          >
          <input
            type="file"
            ref="uploadExcel"
            v-show="false"
            accept=".xls,.xlsx"
            @change="readExcel($event)"
          />
        </div>
      </div>
    </div>

    <Modal v-model="showModal" width="40" @on-ok="submitUpdate">
      <p slot="header">{{ selectItem.jcdId }}检测点信息详情</p>
      <div>
        <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>所属库区:</span>
          </div>
          <div class="modal-value">{{ selectItem.kqName }}</div>
        </div>
        <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>所属井组:</span>
          </div>
          <div class="modal-value">{{ selectItem.jzName }}</div>
        </div>
        <!-- <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>检测点编号:</span>
          </div>
          <div class="modal-value">{{ selectItem.jcdId }}</div>
        </div> -->
        <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>更新时间:</span>
          </div>
          <div class="modal-value">{{ selectItem.updateTime }}</div>
        </div>
        <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>检测点坐标:</span>
          </div>
          <Input class="modal-value" v-model="itemjcPoint" size="large" />
        </div>
        <!-- <div class="flex-row-start-center wrap">
          <div class="modal-title flex-row-end-center">
            <span>最新数值:</span>
          </div>
          <div class="modal-value">{{ selectItem.updateTime }}</div>
        </div> -->
      </div>
    </Modal>

    <Modal v-model="showDelete" style="width: 200px" @on-ok="submitDelete">
      <p slot="header">删除警告</p>
      <div class="flex-row-center-center warning">确定删除么？</div>
    </Modal>

    <!-- 折线图 -->
    <Modal v-model="showDetailModal" width="60" footer-hide>
      <p slot="header" class="modal-header-title">{{ selectedItem.jcdName }}历年示踪剂浓度变化图</p>
      <div id="time-picker" style="padding-left: 450px">
        <label for="start-month">开始月份:</label>
        <select id="start-month" @onchange="updateEndMonthOptions" />
        <label for="end-month">结束月份:</label>
        <select id="end-month" name="end-month" />
        <button @click="updatePointChart">更新图表</button>
      </div>
      <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
    </Modal>
  </div>
</template>
<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      arrList: [],
      curPage: 0,
      showDelete: false,
      selectId: "",
      itemjcPoint: "",
      showModal: false,
      selectItem: {},
      tableData: [],
      pageSize: 10,
      kqName: "",
      kqNameList: ["金坛","刘庄"],
      jzId: "",
      jzName:"",
      jzIdList: [],
      jzNameList:[],
      jcdId: "",
      jcdIdList: [],
      jcdName: "",
      jcdNameList: [],
      updateTime: "",
      columns: [
        { title: "检测点名称", key: "jcdName" },
        // { title: "检测点编号", key: "jcdId" },
        { title: "所属井组", key: "jzName" },
        { title: "所属库区", key: "kqName" },
        // { title: "井组编号", key: "jzId" },
        // { title: "更新时间", key: "updateTime" },
        { title: "检测点坐标", key: "jcPoint" },
        // { title: "最新数值", key: "updateValue" },
        { title: "操作", key: "action", slot: "action" },
      ],
      showDetailModal: false,
      selectedItem: {},
      pointChart: null,
      jcEventsPoints: [],
      uniqueMonths: [],
    };
  },
  props: {
    jcdInfoList: Array,
    totalLen: Number,
  },
  watch: {
    jcdInfoList(val) {
      this.curPage = 0;
      this.tableData = val;
      // this.kqNameList = [];
      this.jzIdList = [];
      this.jcdIdList = [];
      // this.jzNameList = [];
      this.jcdNameList = [];
      let it = this;
      // val.forEach((ele) => {
      //   if (it.kqNameList.indexOf(ele.kqName) < 0) {
      //     it.kqNameList.push(ele.kqName);
      //   }
      //   if (it.jzIdList.indexOf(ele.jzId) < 0) {
      //     it.jzIdList.push(ele.jzId);
      //   }
      //   if (it.jzNameList.indexOf(ele.jzName) < 0) {
      //     it.jzNameList.push(ele.jzName);
      //   }
      //   if (it.jcdIdList.indexOf(ele.jcdId) < 0) {
      //     it.jcdIdList.push(ele.jcdId);
      //   }
      //   if (it.jcdNameList.indexOf(ele.jcdName) < 0) {
      //     it.jcdNameList.push(ele.jcdName);
      //   }
      // });
    },
  },
  created(){
    console.log("组件初始化")
    this.getJzNameList()
    // console.log(<Table/>)
  },

  methods: {
    selKqName(event){
      this.getJzNameList()
    },
    getJzNameList(){
      let param={kqName:this.kqName};
      this.$axios
        .post("/getJzNameList", param, {
          headers: { "Content-Type": "application/json;charset=UTF-8" },
        })
        .then((response) => {
            console.log(response.data)
            if(response.data!=null)
            {
              this.jzNameList=response.data;
            }
        })
        .catch((error) => {});
    },

    importExcel() {
      this.$refs.uploadExcel.click();
    },
    readExcel(e) {
      this.arrList = [];
      const files = e.target.files;
      if (files.length <= 0) {
        //如果没有文件名
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = this.XLSX.read(data, {
            type: "binary",
          });

          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //获取到XLSX表格中的数据,并生成json格式的数据类型
          let arr = [];
          ws.forEach((item) => {
            arr.push({
              jcdName: item["检测点名称"],
              jzName: item["所属井组"],
              jcdPoint: item["坐标"],
            });
          });
          console.log(arr)
          // for (let i in arr) {
          //   let item = arr[i];
          //   for (let key in item) {
          //     // console.log(item[key]);
          //     if (item[key] == "undefined") {
          //       delete item[key];
          //     }
          //   }
          // }

          let it = this;
          arr.forEach((item) => {
            let arr = [];
            let jcdXpoint = "";
            let jcdYpoint = "";
            let o = {};
            o.jcdName = item.jcdName;
            o.jzName = item.jzName;
            if (
              item.jcdPoint != "" &&
              item.jcdPoint.indexOf("(") > -1 &&
              item.jcdPoint.indexOf(")") > -1
            ) {
              let start = item.jcdPoint.indexOf("(");
              let end = item.jcdPoint.indexOf(")");
              let ele = item.jcdPoint.substring(start + 1, end);
              arr = ele.split(",");
              jcdXpoint = arr[0];
              jcdYpoint = arr[1];
            }
            o.jcdYpoint = jcdYpoint;
            o.jcdXpoint = jcdXpoint;
            it.arrList.push(o);
          });
          console.log("it.arrList",it.arrList)
          this.postData();
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    postData() {
      let param = {};
      param.jcdList = JSON.stringify(this.arrList);
      this.$qs.stringify(param, { arrayFormat: "indices", allowDots: true }),
        this.$axios
          .post("/mutipleImportJcdInfo", param, {
            headers: { "Content-Type": "application/json;charset=UTF-8" },
          })
          .then((response) => {
            if(response.data==true)
            {
              console.log("导入成功");
              alert("导入成功");
            }
            else{
              console.log("导入失败");
              alert("导入失败");
            }
          })
          .catch((error) => {});
    },
    deleteItem(row, index) {
      this.selectId = index;
      this.selectItem = row;
      this.showDelete = true;
    },
    submitDelete() {
      let param = {};
      let it = this;
      param.jcdId = this.selectItem.jcdId;
      this.$axios({
        url: "/deleteOneJcdInfo",
        type: "post",
        params: param,
      })
        .then((res) => {
          if (res.data) {
            alert("已删除");
            let o = {};
            if (it.kqName == "" || it.kqName == undefined) {
              it.kqName = "";
            }
            if (it.jzId == "" || it.jzId == undefined) {
              it.jzId = "";
            }
            if (it.jzName == "" || it.jzName == undefined) {
              it.jzName = "";
            }
            if (it.jcdId == "" || it.jcdId == undefined) {
              it.jcdId = "";
            }
            if (it.updateTime == "" || it.updateTime == undefined) {
              it.updateTime = "";
            }
            if (it.jcdName == "" || it.jcdName == undefined) {
              it.jcdName = "";
            }
            o.kqName = it.kqName;
            o.jzId = it.jzId;
            o.jzName = it.jzName;
            o.jcdId = it.jcdId;
            o.updateTime = it.updateTime;
            o.jcdName = it.jcdName;
            if (res.data <= this.pageSize * this.curPage && res.data > 0) {
              o.page = this.curPage - 2;
            } else {
              o.page = this.curPage -1;
            }
            this.$emit("update-jcdInfo", o);
          } else {
            alert("删除失败");
          }
        })
        .catch((error) => {});
    },
    updateItem(item, id) {
      this.selectId = id;
      this.selectItem = item;
      this.itemjcPoint = this.selectItem.jcPoint;
      this.showModal = true;
    },
    submitUpdate() {
      let xPoint = "";
      let yPoint = "";
      if (this.itemjcPoint != "") {
        if (
          this.itemjcPoint.indexOf("(") > -1 &&
          this.itemjcPoint.indexOf(")") > -1
        ) {
          let start = this.itemjcPoint.indexOf("(");
          let end = this.itemjcPoint.indexOf(")");
          let str = this.itemjcPoint.substring(start + 1, end);
          let arr = str.split(",");
          xPoint = arr[0];
          yPoint = arr[1];
        } else {
          alert("坐标格式错误");
          return false;
        }
      }
      let param = {};
      param.jcdId = this.selectItem.jcdId;
      param.jcXpoint = xPoint;
      param.jcYpoint = yPoint;
      this.$axios({
        url: "/updateOneJcdInfo",
        type: "post",
        params: param,
      })
        .then((res) => {
          let o = {};
          let it = this
          if (it.kqName == "" || it.kqName == undefined) {
            it.kqName = "";
          }
          if (it.jzId == "" || it.jzId == undefined) {
            it.jzId = "";
          }
          if (it.jzName == "" || it.jzName == undefined) {
            it.jzName = "";
          }
          if (it.jcdId == "" || it.jcdId == undefined) {
            it.jcdId = "";
          }
          if (it.updateTime == "" || it.updateTime == undefined) {
            it.updateTime = "";
          }
          if (it.jcdName == "" || it.jcdName == undefined) {
            it.jcdName = "";
          }
          o.kqName = it.kqName;
          o.jzId = it.jzId;
          o.jzName = it.jzName
          o.jcdId = it.jcdId;
          o.updateTime = it.updateTime;
          o.jcdName = it.jcdName;
          o.page = this.curPage-1;
          this.$emit("update-jcdInfo", o);
          alert("修改成功");
        })
        .catch((error) => {});
    },
    addData() {
      this.$emit("switch-to-add", false);
    },
    changeUpdateTime(val) {
      this.updateTime = val;
    },
    changepage(index) {
      let it = this;
      let o = {};

      if (it.kqName == "" || it.kqName == undefined) {
        it.kqName = "";
      }
      if (it.jzId == "" || it.jzId == undefined) {
        it.jzId = "";
      }
      if (it.jzName == "" || it.jzName == undefined) {
        it.jzName = "";
      }
      if (it.jcdId == "" || it.jcdId == undefined) {
        it.jcdId = "";
      }
      if (it.updateTime == "" || it.updateTime == undefined) {
        it.updateTime = "";
      }
      if (it.jcdName == "" || it.jcdName == undefined) {
        it.jcdName = "";
      }
      o.kqName = it.kqName;
      o.jzId = it.jzId;
      o.jzName = it.jzName;
      o.jcdId = it.jcdId;
      o.updateTime = it.updateTime;
      o.jcdName = it.jcdName;
      o.page = index-1;
      this.curPage = index;

      this.$emit("change-to-page", o);
    },
    onQuery() {
      let it = this;
      let o = {};

      if (it.kqName == "" || it.kqName == undefined) {
        it.kqName = "";
      }
      if (it.jzId == "" || it.jzId == undefined) {
        it.jzId = "";
      }
      if (it.jzName == "" || it.jzName == undefined) {
        it.jzName = "";
      }
      if (it.jcdId == "" || it.jcdId == undefined) {
        it.jcdId = "";
      }
      if (it.updateTime == "" || it.updateTime == undefined) {
        it.updateTime = "";
      }
      if (it.jcdName == "" || it.jcdName == undefined) {
        it.jcdName = "";
      }
      o.kqName = it.kqName;
      o.jzId = it.jzId;
       o.jzName = it.jzName;
      o.jcdId = it.jcdId;
      o.updateTime = it.updateTime;
      o.jcdName = it.jcdName;
      o.page = 0;
      this.$emit("change-to-page", o);
      // this.query()
    },
    query() {
      let data = [];
      let it = this;
      if (
        !(
          (it.kqName == "" || it.kqName == undefined) &&
          (it.jzId == "" || it.jzId == undefined) &&
          (it.jcdId == "" || it.jcdId == undefined) &&
          (it.updateTime == "" || it.updateTime == undefined) &&
          (it.jcdName == "" || it.jcdName == undefined)
        )
      ) {
        data = this.jcdInfoList.filter(function (item) {
          return (
            (it.kqName != "" ? item.kqName == it.kqName : true) &&
            (it.jzId != "" ? item.jzId == it.jzId : true) &&
            (it.jcdId != "" ? item.jcdId == it.jcdId : true) &&
            (it.updateTime != "" ? item.updateTime == it.updateTime : true) &&
            (it.jcdName !== "" ? item.jcdName == it.jcdName : true)
          );
        });
        this.tableData = data;
      } else {
        this.tableData = this.jcdInfoList;
      }
    },
    showDetail(row, index) {
      this.selectedItem = row;
      this.showDetailModal = true;
      this.$nextTick(() => {
        this.initChart();
        this.fetchChartData();
      });
    },

    initChart() {
      if (this.pointChart) {
        this.pointChart.dispose();
      }
      this.pointChart = echarts.init(this.$refs.chartContainer);
    },

    fetchChartData() {
      this.$axios.get('/getDMkqJcdStatisticsDataByJcdId/' + this.selectedItem.jcdId)
          .then(response => {
            this.jcEventsPoints = response.data.map(item => {
              let jcTime = new Date(item.jcTime);
              return [jcTime.getFullYear() + "-" + (jcTime.getMonth() + 1) + "-" + jcTime.getDate(), item.jcValue];
            });
            this.initLineChart(this.jcEventsPoints);
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
    },

    initLineChart(data) {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'time',
          boundaryGap: false,
          axisLabel: {
            formatter: function (value) {
              const date = new Date(value);
              return date.getFullYear() + '-' + (date.getMonth() + 1);
            }
          }
        },
        yAxis: {
          type: 'value',
          min: 'dataMin', // 自动设置 y 轴的最小值
          max: 'dataMax', // 自动设置 y 轴的最大值
          axisLabel: {
            formatter: function (value) {
              // 控制小数位数并使用大写 E
              return value.toExponential(5).replace('e', 'E')
            }
          }
        },
        dataZoom: [
          {
            type: 'slider',
            start: 0,
            end: 100
          },
          {
            type: 'inside',
            start: 0,
            end: 100
          }
        ],
        series: [{
          name: '数据',
          type: 'line',
          data: data,
          markPoint: {
            data: data.map(item => ({
              coord: item,  // 直接标注每个数据点
              label: {
                show: true,
                formatter: function (params) {
                  return item[1].toExponential(2).replace('e', 'E') + '\n' + (new Date(item[0]).getFullYear().toString().slice(-2) + '-' + (new Date(item[0]).getMonth() + 1) + '-' + new Date(item[0]).getDate());
                },
                backgroundColor: 'rgb(236,10,10)',
                borderColor: '#ccc',
                borderWidth: 1,
                padding: [5, 1],
                borderRadius: 3,
                fontSize: 12  // 调整字体大小
              }
            }))
          }
        }]
      };

      this.pointChart.setOption(option);

      const startMonthDom = document.getElementById('start-month');
      const endMonthDom = document.getElementById('end-month');

      this.uniqueMonths = [...new Set(this.jcEventsPoints.map(item => {
        const jcTime = new Date(item[0]);
        return jcTime.getFullYear() + '-' + (jcTime.getMonth() + 1).toString().padStart(2, '0');
      }))];

      startMonthDom.innerHTML = '';
      endMonthDom.innerHTML = '';
      this.uniqueMonths.forEach(month => {
        const option = document.createElement('option');
        option.value = month;
        option.text = month;
        startMonthDom.appendChild(option);
        endMonthDom.appendChild(option.cloneNode(true));
      });
    },
    updateEndMonthOptions() {
      const startMonthDom = document.getElementById('start-month');
      const endMonthDom = document.getElementById('end-month');
      endMonthDom.innerHTML = '';

      this.uniqueMonths.forEach(month => {
        if (month >= startMonthDom.value) {
          const option = document.createElement('option');
          option.value = month;
          option.text = month;
          endMonthDom.appendChild(option);
        }
      });
    },
    updatePointChart() {
      const startMonth = document.getElementById('start-month').value;
      const endMonth = document.getElementById('end-month').value;
      const filteredData = this.jcEventsPoints.filter(item => {
        const jcTime = new Date(item[0]);
        const month = jcTime.getFullYear() + '-' + (jcTime.getMonth() +  1).toString().padStart(2, '0');
        console.log(month)
        return month >= startMonth && month <= endMonth;
      });

      this.pointChart.setOption(
          {
            series: [{
              name: '数据',
              type: 'line',
              data: filteredData
            }]
          }
      )
    }
  }
};
</script>
<style scoped>
.test-style {
  color: black;
  font-size: 18px;
  text-align: left;
  font-family: SourceHanSansSC-regular;
  width: calc(12.5% - 10px);

  margin-right: 10px;
}
.modal-title {
  width: 25%;
  margin-right: 5%;
  font-size: 16px;
  font-weight: 600;
}
.modal-value {
  width: 40%;
  font-size: 16px;
}
.hover-icon:hover {
  cursor: pointer;
}
.wrap {
  height: 45px;
}
.warning {
  height: 60px;
  font-size: 20px;
  font-weight: 600;
}

.modal-header-title {
  font-size: 18px;
  text-align: center;
  margin: 0;
  padding: 10px 0 25px;
}

</style>